package com.system.config.mybatis.plugins;

import com.alibaba.fastjson.JSON;
import org.apache.ibatis.executor.resultset.DefaultResultSetHandler;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.*;
import org.springframework.util.ReflectionUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * 获取到查询结果后 ，执行顺序 3
 */
@Intercepts({@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})})
public class ResultSetInterceptor implements Interceptor {
    /**
     * @param invocation
     * @return  是 List<Object> 查询结果
     * @throws Throwable
     */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        System.out.println("C: invocation " + invocation.getTarget().getClass() + " | " + invocation.getMethod().getName() + " | " + Arrays.asList(invocation.getArgs()));
        if (invocation.getTarget() instanceof ResultSetHandler) {
            DefaultResultSetHandler target = (DefaultResultSetHandler) invocation.getTarget();
            Field boundSqlField = ReflectionUtils.findField(target.getClass(), "boundSql");
            boundSqlField.setAccessible(true);
            BoundSql boundSql = (BoundSql) boundSqlField.get(target);
            String sql = boundSql.getSql();
            List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
            Object parameterObject = boundSql.getParameterObject();
            System.out.println(sql);System.out.println(JSON.toJSONString(parameterMappings));System.out.println(JSON.toJSONString(parameterObject));
            // 此处存redis 操作
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof ResultSetHandler) {
            return Plugin.wrap(target,this);
        }
        return target;
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
